package com.brsya.movie.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.brsya.base.base.BaseMvpFragment;
import com.brsya.base.base.Contents;
import com.brsya.base.bean.MovieBean;
import com.brsya.base.bean.MovieListBean;
import com.brsya.base.recycler.BaseAdapter;
import com.brsya.base.recycler.BaseItemBean;
import com.brsya.base.recycler.BaseViewHolder;
import com.brsya.base.util.LoggerUtil;
import com.brsya.movie.R;
import com.brsya.movie.activity.FindActivity;
import com.brsya.movie.activity.PlayActivity;
import com.brsya.movie.activity.WebPageActivity;
import com.brsya.movie.adapter.BannerAdapter;
import com.brsya.movie.adapter.MovieListAdapter;
import com.brsya.movie.contract.MovieListContract;
import com.brsya.movie.presenter.MovieListPresenter;
import com.brsya.movie.util.AppUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by Brsya
 * CreateDate: 2022/6/29  20:16
 * Description:
 * 首页-精选
 */
public class MovieListFragment extends BaseMvpFragment<MovieListPresenter> implements MovieListContract.View, View.OnClickListener {

    private static final int BANNER_AUTO_TIME = 7000;


    private SwipeRefreshLayout srlRefreshBox;
    private RecyclerView rlList;

    private ViewPager vpBannerBox;
    private TextView tvPagerNumber;
    private LinearLayout llListTabHot;
    private LinearLayout llListTabRanking;
    private LinearLayout llListTabCollection;
    private LinearLayout llListTabVideo;

    private MovieListAdapter movieAdapter;

    private BannerAdapter bannerAdapter;

    private BaseAdapter<MovieListBean.ContentListDTO> tabAdapter;

    /**
     * 是否初次进入
     */
    private boolean isFirst = true;

    /**
     * 分类标示
     */
    private String code;
    private LinearLayout llTopTabBox;
    private RecyclerView rlTopTypeBox;

    /**
     * banner数据
     */
    private List<MovieListBean.BannerListDTO> bannerList;

    private Handler handler;

    /**
     * 轮播图自动切换
     */
    private Runnable bannerRunnable;

    private int selectBannerIndex = 0;

    private OnClickTabListener onClickTabListener;

    public static MovieListFragment newInstance(String code) {

        Bundle args = new Bundle();
        args.putString("code", code);
        MovieListFragment fragment = new MovieListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setArguments(@Nullable Bundle args) {
        super.setArguments(args);
        if (args != null) {
            code = args.getString("code");
        }
    }

    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_movie_list);

        srlRefreshBox = findViewById(R.id.srl_refresh_box);
        rlList = findViewById(R.id.rl_list);

        srlRefreshBox.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                presenter.getMovieList(code);
            }
        });


        rlList.setLayoutManager(new LinearLayoutManager(getContext()));
        rlList.setAdapter(movieAdapter = new MovieListAdapter(getActivity()));

        movieAdapter.setOnRefreshListener(new MovieListAdapter.OnRefreshListener() {
            @Override
            public void onRefresh(int position, MovieListBean.ContentListDTO bean) {

                int page = bean.getPage();
                int newPage;
                if (page + 1 > bean.getTotal()) {
                    newPage = 1;
                } else {
                    newPage = bean.getTotal();
                }
                presenter.getMovieList(bean.getHvId(), String.valueOf(newPage));
            }
        });

        initTop();
    }

    /**
     * 初始化头部布局
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initTop() {
        handler = new Handler(Looper.getMainLooper());

        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.top_movie_list, null, false);

        movieAdapter.setHeaderView(headerView);
        // 头部View
        vpBannerBox = headerView.findViewById(R.id.vp_banner_box);
        tvPagerNumber = headerView.findViewById(R.id.tv_pager_number);
        llListTabHot = headerView.findViewById(R.id.ll_list_tab_hot);
        llListTabRanking = headerView.findViewById(R.id.ll_list_tab_ranking);
        llListTabCollection = headerView.findViewById(R.id.ll_list_tab_collection);
        llListTabVideo = headerView.findViewById(R.id.ll_list_tab_video);
        llTopTabBox = headerView.findViewById(R.id.ll_top_tab_box);
        rlTopTypeBox = headerView.findViewById(R.id.rl_top_type_box);


        if (code == null) {
            llTopTabBox.setVisibility(View.VISIBLE);
//            llTopTabBox.setVisibility(View.GONE);
            rlTopTypeBox.setVisibility(View.GONE);
        } else {
            llTopTabBox.setVisibility(View.GONE);
            rlTopTypeBox.setVisibility(View.VISIBLE);
            rlTopTypeBox.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
            rlTopTypeBox.setAdapter(tabAdapter = new BaseAdapter<MovieListBean.ContentListDTO>() {
                @Override
                public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                    View rootView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie_list_top_type, parent, false);
                    return new BaseViewHolder(rootView);
                }

                @Override
                public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieListBean.ContentListDTO data) {
                    TextView tvTab = viewHolder.findViewById(R.id.tv_type);
                    tvTab.setText(data.getTitle());
                }
            });
            tabAdapter.setOnItemClickListener((position, bean) -> {
                // 2022/7/6 进入片单页面
                String imgUrl;
                if (bean.getVideoList() != null && bean.getVideoList().size() > 0) {
                    imgUrl = bean.getVideoList().get(0).getCoverUrl();
                } else {
                    imgUrl = null;
                }
                AppUtil.openInventoryDetail(getContext(), bean.getHvId(), bean.getTitle(), imgUrl);
            });
        }

        vpBannerBox.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvPagerNumber.setText(String.format(Locale.getDefault(), "%d/%d", position + 1, bannerAdapter.getCount()));
                selectBannerIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vpBannerBox.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        stopBannerAuto();
                        break;
                    case MotionEvent.ACTION_UP:
                        startBannerAuto();
                        break;
                }


                return false;
            }
        });


        llListTabHot.setOnClickListener(this);
        llListTabRanking.setOnClickListener(this);
        llListTabCollection.setOnClickListener(this);
        llListTabVideo.setOnClickListener(this);
    }

    /**
     * 开始播放轮播图
     */
    private void startBannerAuto() {
        if (handler != null && bannerRunnable != null) {
            handler.removeCallbacks(bannerRunnable);
//            LoggerUtil.e("添加自动播放");
            handler.postDelayed(bannerRunnable, BANNER_AUTO_TIME);
        }
    }

    /**
     * 结束播放轮播图
     */
    private void stopBannerAuto() {
        if (handler != null && bannerRunnable != null) {
//            LoggerUtil.e("删除自动播放");
            handler.removeCallbacks(bannerRunnable);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_list_tab_hot) {
            if (onClickTabListener != null) {
                onClickTabListener.onClickTab(0);
            }
        } else if (id == R.id.ll_list_tab_ranking) {// 进入片单页面
            Intent tanking = new Intent(getActivity(), FindActivity.class);
            tanking.putExtra(Contents.INTENT_FIND_SELECT, FindFragment.SELECT_RANKING);
            startActivity(tanking);
        } else if (id == R.id.ll_list_tab_collection) {// 进入片单页面
            Intent collection = new Intent(getActivity(), FindActivity.class);
            collection.putExtra(Contents.INTENT_FIND_SELECT, FindFragment.SELECT_LIST);
            startActivity(collection);
        } else if (id == R.id.ll_list_tab_video) {
            if (onClickTabListener != null) {
                onClickTabListener.onClickTab(1);
            }
        }
    }

    @Override
    protected void initData() {
        if (code == null) {
            presenter.getMovieList(null);
            isFirst = false;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LoggerUtil.e("隐藏状态：" + hidden);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirst && code != null && presenter != null) {
            presenter.getMovieList(code);
            isFirst = false;
        }
        startBannerAuto();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopBannerAuto();
    }

    @Override
    public void showMovieList(List<MovieListBean.ContentListDTO> movieList) {
        List<BaseItemBean> list = new ArrayList<>(movieList.size());

        for (int i = 0; i < movieList.size(); i++) {
            MovieListBean.ContentListDTO contentListDTO = movieList.get(i);
            contentListDTO.setPage(1);
            if (contentListDTO.getListNum() % 6 > 0) {
                contentListDTO.setTotal(contentListDTO.getListNum() / 6 + 1);
            } else {
                contentListDTO.setTotal(contentListDTO.getListNum() / 6);
            }
            list.add(contentListDTO);
            if (i == 0) {
                BaseItemBean baseItemBean = new BaseItemBean();
                baseItemBean.setItemType(MovieListAdapter.LAYOUT_TYPE_AD_VIDEO);
                list.add(baseItemBean);
            }
            BaseItemBean baseItemBean = new BaseItemBean();
            baseItemBean.setItemType(MovieListAdapter.LAYOUT_TYPE_AD);
            list.add(baseItemBean);
        }

        movieAdapter.setDataList(list);
        movieAdapter.notifyDataSetChanged();
    }

    @Override
    public void showBanner(List<MovieListBean.BannerListDTO> bannerLists) {
        if (bannerLists == null) {
            movieAdapter.setHeaderView(null);
            return;
        }
        this.bannerList = bannerLists;
        if (bannerAdapter == null) {
            vpBannerBox.setAdapter(bannerAdapter = new BannerAdapter(getActivity()));
            bannerAdapter.setOnItemClickListener(new BannerAdapter.OnItemClickListener<MovieListBean.BannerListDTO>() {
                @Override
                public void onItemClick(int position, MovieListBean.BannerListDTO data) {
                    Intent intent;
                    if (data.getType() == 10) {
                        intent = new Intent(getActivity(), PlayActivity.class);
                        MovieBean movieBean = new MovieBean();
                        movieBean.setId(Integer.parseInt(data.getLinkId()));
                        movieBean.setName(data.getTitle());
                        movieBean.setCoverUrl(data.getImgUrl());
                        intent.putExtra(Contents.INTENT_MOVIE_DETAIL, movieBean);
                    } else {
                        intent = new Intent(getActivity(), WebPageActivity.class);
                        intent.putExtra(Contents.INTENT_H5_URL, data.getLinkId());
                    }
                    startActivity(intent);
                }

                @Override
                public void adClose() {
                    vpBannerBox.setCurrentItem(0);
                }
            });
        }
        vpBannerBox.setOffscreenPageLimit(bannerList.size());
        bannerAdapter.setBannerList(bannerList);
        tvPagerNumber.setText(String.format(Locale.getDefault(), "1/%d", bannerAdapter.getCount()));

        if (bannerRunnable == null) {
            bannerRunnable = new Runnable() {
                @Override
                public void run() {
                    if (bannerAdapter == null) {
                        handler.postDelayed(bannerRunnable, BANNER_AUTO_TIME);
                        return;
                    }
                    if (bannerAdapter.getCount() > selectBannerIndex + 1) {
                        vpBannerBox.setCurrentItem(selectBannerIndex + 1);
                    } else {
                        vpBannerBox.setCurrentItem(0);
                    }
                    handler.postDelayed(bannerRunnable, BANNER_AUTO_TIME);
                }
            };
            handler.postDelayed(bannerRunnable, BANNER_AUTO_TIME);
        }


    }

    @Override
    public void showTab(List<MovieListBean.ContentListDTO> tabList) {
        if (tabList == null) {
            return;
        }
        tabAdapter.setDataList(tabList);
        tabAdapter.notifyDataSetChanged();
    }

    @Override
    public void showMovieListById(int id, String page, List<MovieListBean.ContentListDTO.VideoListDTO> movieList) {
        for (int i = 0; i < movieAdapter.getDataList().size(); i++) {
            BaseItemBean itemBean = movieAdapter.getDataList().get(i);
            if (!(itemBean instanceof MovieListBean.ContentListDTO)) {
                continue;
            }
            MovieListBean.ContentListDTO contentBean = (MovieListBean.ContentListDTO) itemBean;
            if (contentBean.getHvId() == id) {
                contentBean.setVideoList(movieList);
                contentBean.setPage(Integer.parseInt(page));
                movieAdapter.notifyChangedPosition(i);
                break;
            }
        }
    }

    @Override
    protected void initPresenter() {
        presenter = new MovieListPresenter();
        presenter.attachView(this);
    }

    @Override
    public void showLoading() {
        srlRefreshBox.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        srlRefreshBox.setRefreshing(false);
    }


    public void setOnClickTabListener(OnClickTabListener onClickTabListener) {
        this.onClickTabListener = onClickTabListener;
    }

    /**
     * 点击精选tab
     */
    public interface OnClickTabListener {
        /**
         * 点击精选tab
         *
         * @param type 0 热门 1 短视频
         */
        void onClickTab(int type);
    }
}
